#coding=utf-8

'''
threadlocals middleware

from http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser


settings.py

    MIDDLEWARE_CLASSES = (
        ...
        "middleware.threadlocals.ThreadLocals",
        ...
    )

apps/news/models_old.py


from django.db import models
from django.contrib.auth.models import User

class NewsItem(models.Model):
    owner = models.ForeignKey(User,related_name="owner",blank=True, editable=False)
    last_edited_by = models.ForeignKey(User,related_name="last_edited_by",blank=True, editable=False)
    text = models.TextField()

apps/news/models_new.py

from django.db import models
from django.contrib.auth.models import User
from yourproject.middleware import threadlocals

class NewsItem(models.Model):
    owner = models.ForeignKey(User,related_name="owner",blank=True)
    last_edited_by = models.ForeignKey(User,related_name="last_edited_by",blank=True)
    text = models.TextField()

    # Set the owner and last_edited_by when appropriate
    def save(self):
        # If the object already existed, it will already have an id
        if self.id:
            # This object is being edited, not saved, set last_edited_by
            self.last_edited_by = threadlocals.get_current_user()
        else:
            # This is a new object, set the owner
            self.owner = self.last_edited_by = threadlocals.get_current_user()
        super(NewsItem,self).save()

'''
try:
    from threading import local
except ImportError:
    from django.utils._threading_local import local

_thread_locals = local()


def get_current_user():
    return getattr(_thread_locals, 'user', None)

class ThreadLocals(object):
    """Middleware that gets various objects from the
    request object and saves them in thread local storage.
    """

    def process_request(self, request):
        _thread_locals.user = getattr(request, 'user', None)
